package cn.itsource.controller;


import cn.itsource.hrm.doc.CourseDoc;
import cn.itsource.hrm.doc.CourseOnlineVo;
import cn.itsource.hrm.util.AjaxResult;
import cn.itsource.hrm.util.PageList;
import cn.itsource.repository.CourseRepository;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * @author jinhui
 * @version V1.0.0
 * @date 2020/6/3
 */
@RestController
@RequestMapping("/course")
public class CourseEsController {

    @Autowired
    private CourseRepository courseRepository;
    
    @PostMapping("/save")
    public AjaxResult save(@RequestBody CourseDoc courseDoc){
        try {
            courseRepository.save(courseDoc);
            return AjaxResult.me().setSuccess(true).setMessage("上线成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("上线失败");
        }
    }
    @PostMapping("/saveBatch")
    public AjaxResult saveBatch(@RequestBody List<CourseDoc> courseDocs){
        try {
            courseRepository.saveAll(courseDocs);
            return AjaxResult.me().setSuccess(true).setMessage("批量上线成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("批量上线失败"+e.getMessage());
        }
    }

    @DeleteMapping ("/delete")
    public AjaxResult delete(@RequestBody Long id){
        try {
            courseRepository.deleteById(id);
            return AjaxResult.me().setSuccess(true).setMessage("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败");
        }
    }

    @PostMapping ("/deleteBatch")
    public AjaxResult deleteBatch(@RequestBody List<Long> ids){
        try {
            for (Long id:ids){
                courseRepository.deleteById(id);
            }
            return AjaxResult.me().setSuccess(true).setMessage("批量删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("批量删除失败");
        }
    }

    /**
     * 前台用户检索上线的课程
     * @return
     */
    @PostMapping("/searchOnline")
    public PageList<CourseDoc> searchOnline(@RequestBody CourseOnlineVo vo){

        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        //query
        BoolQueryBuilder bool = new BoolQueryBuilder();
        //关键字查询
        if(!StringUtils.isEmpty(vo.getKeyword())){
            bool.must(new MatchQueryBuilder("all",vo.getKeyword()));
        }
        List<QueryBuilder> filters = bool.filter();
        //课程类型过滤
        if(vo.getCourseTypeId()!=null){
            filters.add(new TermQueryBuilder("courseTypeId",vo.getCourseTypeId()));
        }
        //机构id过滤
        if(vo.getTenantId()!=null){
            filters.add(new TermQueryBuilder("tenantId",vo.getTenantId()));
        }
        //价格的过滤,如果没有输入价格的过滤条件，默认查询价格>=0的

        if(vo.getMinPrice()!=null){
            RangeQueryBuilder rangeQueryBuilder = new RangeQueryBuilder("price");
            rangeQueryBuilder.gte(vo.getMinPrice());
            filters.add(rangeQueryBuilder);

        }
        if(vo.getMaxPrice()!=null){
            RangeQueryBuilder rangeQueryBuilder = new RangeQueryBuilder("price");
            rangeQueryBuilder.lte(vo.getMaxPrice());
            filters.add(rangeQueryBuilder);
        }

        builder.withQuery(bool);


        //sort 排序列
        String filedName = "";
        if("xp".equals(vo.getOrderField())){
            filedName = "startTime";
        }else{
            filedName = "price";
        }
        //排序方式
        SortOrder order = null;
        if("asc".equals(vo.getOrderType())){
            order = SortOrder.ASC;
        }else{
            order = SortOrder.DESC;
        }
        builder.withSort(new FieldSortBuilder(filedName).order(order));

        //from是从0开始的 size
        builder.withPageable(PageRequest.of(vo.getPageNum()-1,vo.getPageSize()));
        Page<CourseDoc> page = courseRepository.search(builder.build());
        return new PageList<>(page.getTotalElements(),page.getContent());

    }



}
